const Koa = require('koa');
const logger = require('./logs/logger');
const routers = require('./routers').routes();
const openurl = require('openurl');
const config = require('./config');

const app = new Koa();

// error handle
app.use(async (ctx, next) => {
    try{
        await next();
    } catch(e) {
        logger.debug(e);
        app.emit('error', e, ctx);
    }
});

app.use(require('koa2-cors')());
app.use(routers);

const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);

let _prot = 0;
let _msgs = [];

module.exports = {
    start() {
        if (!server.listening) {
            server.listen(config.port);
        }
        return this;
    },

    open(){
        if (server.listening) {
            openurl.open(`http://localhost:${config.port}`);
        }
        return this;
    },

    withSocket(){
        var msg_resp = io.of('/msg_resp');

        io.of('/msg_req').on('connection', socket=>{
            socket.on('clear', ()=>{
                _msgs = [];
            });

            socket.on('fetch', msgs => {
                _msgs = _msgs.concat(msgs);

                logger.debug(_msgs);
            });

            socket.on('pop', ()=>{
                msg_resp.emit('pop', _msgs.pop());
            })
        });

        return this;
    }
};